require 'mp3info'
class Broadcast < ActiveRecord::Base
  belongs_to              :program
  has_many                :occurrences
  has_and_belongs_to_many :audio_assets
  has_and_belongs_to_many :schedules
  
  after_save              :replicate_assets

  validates_presence_of   :name, :short_description

  acts_as_authorizable
  acts_as_taggable
  
  LANGUAGES = %w(English Portuguese Vietnamese Zulu)
  GENRES = Mp3Info::GENRES.sort
  
  def self.search(keys)
    conditions = []    
    search_columns = %w(name short_description description)
    search_columns.each { |element| conditions << (element + " LIKE '%#{keys}%'") }
    
    Broadcast.find :all, :conditions => conditions.join(' or '), :order => :name
  end
  
  def add_tags(tags)
    self.tag_list.add(tags)
  end
  
  
  def tag_cloud
    self.tag_list.blank? ? [] : self.tag_counts
  end
  
  # Class method for retrieve tag_cloud
  def self.tag_cloud
    self.tag_counts.blank? ? [] : self.tag_counts
  end
  
  def self.top_tagged(limit = 10)
    total = Broadcast.tag_cloud.size
    return nil if total.zero?
    
    limit = (limit > total) ? total : limit
    
    Broadcast.tag_cloud.sort_by(&:count).reverse[0..(limit - 1)]
  end
  
  def self.find_by_tags(tags)
    self.find_tagged_with tags
  end
  
  def self.find_recent(limit = 3)
    self.find :all, :order => 'created_at desc', :limit => limit
  end
  
  ########################################
  # Authorization methods
  #######################################
  def is_updatable_by(user)
    return false if user.blank?
    current_user.has_role? Role::Author, self
  end
  
  def is_deletable_by(user)
    return false if user.blank?
    true
  end
  
  def self.is_readable_by(user, object = nil)
    return false if user.blank?
    true
  end
  
  def self.is_creatable_by(user, program)
    return false if user.blank?
	
	if program.nil?
	  user.has_role? Role::Editor
	else
	  user.has_role? Role::Author, program
	end
  end
  #########################################
  
  def add_asset(asset)
    self.audio_assets << asset unless asset.nil?
  end

  private
  # After save the broadcast, mark its audio_assets to replicate
  def replicate_assets
    unless self.audio_assets.nil? or self.audio_assets.blank?    
      self.program.replica_systems.each do |replica|
        self.audio_assets.each do |asset|
          asset.replicate(replica)
        end
      end
    end
  end
  
end
